package homework.course.role;

import homework.course.Message;
import homework.course.MessageType;
import homework.course.role.state.DistractedState;
import homework.course.role.state.PlayingState;
import homework.course.role.state.SleepState;
import homework.course.role.state.StudentState;
import homework.util.observer.Observable;

import java.util.Iterator;

public class Teacher extends Animal implements Classable {

    private String name;
    private Iterator<String> speech;

    public Teacher(String name, Iterator<String> speech) {
        this.name = name;
        this.speech = speech;
    }

    public void pollStudent(Student student) {
        StudentState state = student.getCurrentState();
        if(state instanceof PlayingState) {
            ((PlayingState) state).forfeit();
        } else if(state instanceof SleepState) {
            student.wakeUp();
        } else {
            student.setState(student.getConcentrateState());
        }
    }

    public void pollAllStudents(Student[] students) {
        notifyObservers(new Message("下位巡查", MessageType.SYSTEM));
        for(Student student: students)
            pollStudent(student);
    }

    public void askQuestion(Student[] students) {
        Student std = students[(int)Math.floor(Math.random()*students.length)];
        String msg = String.format("请%s同学回答问题", std.getName());
        notifyObservers(new Message(msg, MessageType.WORDS));
        std.speak();
    }

    @Override
    public String speak() {
        String msg = null;
        if(speech.hasNext()) {
            msg = speech.next();
            notifyObservers(new Message(msg, MessageType.WORDS));
        } else {
            notifyObservers(null);
        }
        return msg;
    }

    @Override
    public void listen(Object obj, String msg) {
        notifyObservers(new Message("不听不听我不听", MessageType.WORDS));
    }

    @Override
    public void receive(Observable observable, Object obj) {
        listen(observable, obj.toString());
    }

    @Override
    public String toString() {
        return name+"老师";
    }
}
